import cv2
import numpy as np
import pyautogui
import time
import keyboard
import pydirectinput

# 捕捉敌人攻击特效颜色
class get_img_contours:
    def __init__(self, lower_hsv, upper_hsv, screenshot):
        self.lower_hsv = lower_hsv
        self.upper_hsv = upper_hsv
        self.screenshot = screenshot
        self.img = cv2.cvtColor(np.array(self.screenshot), cv2.COLOR_RGB2BGR)
        self.hsv_img = cv2.cvtColor(self.img, cv2.COLOR_BGR2HSV)

    def get_contours(self):
        mask = cv2.inRange(self.hsv_img, self.lower_hsv, self.upper_hsv)
        
        kernel = np.ones((5, 5), np.uint8)
        mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)

        contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
        return contours
    
# 计算轮廓高度与宽度
def get_rectangle(contours):
    rectangle_info = []
    # 绘制矩形框
    for contour in contours.get_contours():
        x, y, w, h = cv2.boundingRect(contour)
        rectangle_info.append((w, h))
    return rectangle_info

if __name__ == "__main__":

    time.sleep(2)

    width, height = pyautogui.size()

    while True:
        if keyboard.is_pressed('`'):
            print("程序已停止")
            break

        # 传入自定义的黄色光效
        lower_hsv_yellow = np.array([20, 108, 236])
        upper_hsv_yellow = np.array([40, 235, 255])

        # 传入自定义的红色光效
        lower_hsv_red = np.array([0, 70, 240])
        upper_hsv_red = np.array([180, 160, 255])

        # 截图
        screenshot = pyautogui.screenshot(region=(0, 0, width, height))

        # 创建类的实例
        contours_yellow = get_img_contours(lower_hsv_yellow, upper_hsv_yellow, screenshot)
        contours_red = get_img_contours(lower_hsv_red, upper_hsv_red, screenshot)

        w_h_list_yellow = get_rectangle(contours_yellow)
        w_h_list_red = get_rectangle(contours_red)

        # 设置全局延迟为0
        pydirectinput.PAUSE = 0

        # 自定义短延迟,单位s
        short_delay = 0.02
        mid_delay = 0.06
        long_delay = 0.8

        if any(w > 300 and h <= 30 or w <= 30 and h > 300 for w, h in w_h_list_yellow):
            time.sleep(0.01)
            pydirectinput.press('shift') # 冲刺
            time.sleep(short_delay)
            pydirectinput.press('j') # 攻击
            time.sleep(mid_delay)
            pydirectinput.press('space') # 换人
            time.sleep(long_delay)
            pydirectinput.press('j') # 攻击
            print("yellow")
            time.sleep(0.5)
        elif any(w > 300 and h <= 30 or w <= 30 and h > 300 for w, h in w_h_list_red):
            time.sleep(0.03)
            pydirectinput.press('shift')
            time.sleep(short_delay)
            pydirectinput.press('j')
            time.sleep(mid_delay)
            pydirectinput.press('space')
            time.sleep(short_delay)
            pydirectinput.press('j')
            print("red")
            time.sleep(0.3)
        
        time.sleep(0.01)